package com.project.Service.impl;


import com.project.Bean.User;
import com.project.Service.IUserService;
import com.project.mapper.IUserMapper;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * 用户实现类
 */
public class IUserServiceImpl extends BaseService implements IUserService {

    @Override
    public User login(String name, String pwd) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        User user =  mapper.login(name,pwd);

        session.close();
        return user;
    }

    @Override
    public List<User> findAll() {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        List<User> list = mapper.findAll();
        session.close();
        return list;

    }
    public User findUserName(User user){
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        User user1 = mapper.findUserName(user);
        session.close();
        return user1;
    }
    @Override
    public boolean addUser(User user) {

        if(findUserName(user) != null){
            return false;
        }
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        mapper.addUser(user);
        session.commit();
        session.close();
        return true;
    }

    @Override
    public void delUser(int id) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        mapper.delUser(id);
        session.commit();
        session.close();
    }

    @Override
    public User findById(int id) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
       User user = mapper.findById(id);

        session.close();
        return user;
    }

    @Override
    public void update(int id, String s) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        mapper.update(id,s);
        session.commit();
        session.close();
    }

    @Override
    public String changePwd(User loginUser, String oldPwd, String newPwd, String reNewPwd) {
        if(!oldPwd .equals(loginUser.getPwd()) ){
            return "旧密码不正确";
        }
        else{
           if(!newPwd.equals(reNewPwd)){
              return "两次密码不一致";
           }
           else {
               SqlSession session = this.getSession();
               IUserMapper mapper = session.getMapper(IUserMapper.class);
               mapper.changePwd(findUserName(loginUser).getId(), newPwd);
               session.commit();
               session.close();
           }
        }
        return newPwd;
    }
}
